package com.liukai.todo_android.ui.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatSpinner;

import com.liukai.todo_android.R;
import com.liukai.todo_android.call_back.IUpdateScheduleCallBack;
import com.liukai.todo_android.common.utils.Constants;
import com.liukai.todo_android.common.utils.LogUtils;
import com.liukai.todo_android.entity.ItemVo;
import com.liukai.todo_android.entity.Resp;
import com.liukai.todo_android.entity.vo.UpdateItemVo;
import com.liukai.todo_android.presenter.UpdateSchedulePresenter;
import com.liukai.todo_android.ui.dialog.listener.ModifySuccessListener;
import com.wang.avi.AVLoadingIndicatorView;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/19 9:39 上午
 * @description：修改计时类型对话框
 * @modified By：
 * @version: $
 */
public class ModifyTimingTypeDialog implements IUpdateScheduleCallBack {

    private Context context;
    private final int layoutId = R.layout.dialog_update_timing_type;
    private View view;
    private AlertDialog dialog;
    private AppCompatSpinner timingTypeSpinner;
    private AppCompatSpinner scheduleTypeSpinner;
    private AppCompatButton btnSubmitAttach;
    private TextView btnSave;
    private TextView btnCancel;
    private EditText etScheduleTitle;
    private EditText etScheduleDesc;
    private Integer timingType;
    private EditText etPlanTime;
    private ItemVo itemVo;
    private int planTime;
    private UpdateSchedulePresenter updateSchedulePresenter;
    private AVLoadingIndicatorView avi;
    private AlertDialog.Builder builder;
    private AlertDialog warningDialog;

    public ModifyTimingTypeDialog(Context context, ItemVo itemVo) {
        this.context = context;
        this.itemVo = itemVo;
        createDialog();
        initView();
        initDate();
        initListener();
    }

    private void createDialog() {

        view = View.inflate(context, layoutId, null);
        dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        // 设置点击不可取消
        dialog.setCancelable(false);
        // 获取Window对象
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        // 设置显示视图内容
        window.setContentView(view);
        createAlterDialog();
    }

    private void createAlterDialog() {
        builder = new AlertDialog.Builder(context);
        builder.setTitle("注意!");
        builder.setMessage("只有倒计时和正计时才能使用专注，请修改计时类型，此时退出将会退出专注界面。");
        builder.setCancelable(false);
        builder.setPositiveButton("继续修改", (dialog, which) -> warningDialog.dismiss());
        builder.setNeutralButton("退出专注", (dialog, which) -> {
            warningDialog.dismiss();
            modifySuccessListener.cancel();
        });

    }

    private void initView() {

        timingTypeSpinner = view.findViewById(R.id.timing_type);
        scheduleTypeSpinner = view.findViewById(R.id.schedule_type);
        btnSave = view.findViewById(R.id.btn_save);
        btnCancel = view.findViewById(R.id.btn_cancel);
        etScheduleTitle = view.findViewById(R.id.schedule_title);
        etScheduleDesc = view.findViewById(R.id.schedule_desc);
        etPlanTime = view.findViewById(R.id.planTime);
        avi = view.findViewById(R.id.avi);

    }

    private void initDate() {
        etScheduleTitle.setText(itemVo.getTitle());
        etScheduleDesc.setText(itemVo.getDescription());
    }

    private void initListener() {
        initTimingTypeListener();
        initSaveListener();
        initCancelListener();
    }

    /**
     * 取消
     */
    private void initCancelListener() {
        btnCancel.setOnClickListener(v -> {
//            this.dismiss();
            warningDialog = builder.show();
        });
    }

    /**
     * 保存
     */
    private void initSaveListener() {
        btnSave.setOnClickListener(v -> {
            if (validateSave()) {
                saveClick(v);
            }
        });
    }

    /**
     * 校验能不能保存
     *
     * @return
     */
    private boolean validateSave() {
        if (timingType == Constants.TIMING_TYPE_NO) {
            Toast.makeText(context, "计时类型不能为无，请修改！", Toast.LENGTH_SHORT).show();
            return false;
        }
        planTime = Integer.valueOf(etPlanTime.getText().toString());
        if (timingType == Constants.TIMING_TYPE_DOWN && planTime == 0) {
            Toast.makeText(context, "倒计时时间不能小于等于0，请修改！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 新增保存
     *
     * @param v
     */
    private void saveClick(View v) {

        avi.setVisibility(View.VISIBLE);
        avi.show();
        UpdateItemVo updateItemVo = createUpdateItemVo();
        updateSchedulePresenter = new UpdateSchedulePresenter();
        updateSchedulePresenter.registerCallback(this);
        updateSchedulePresenter.update(updateItemVo);

    }

    /**
     * 创建一个UpdateScheduleVo对象
     */
    private UpdateItemVo createUpdateItemVo() {
        UpdateItemVo updateScheduleVo = new UpdateItemVo();
        updateScheduleVo.setId(itemVo.getId())
                .setFinished(itemVo.getFinished())
                .setAttachment(itemVo.getAttachment())
                .setDescription(itemVo.getDescription())
                .setTitle(itemVo.getTitle())
                .setTimingType((Byte.valueOf(timingType + "")))
                .setConsumePlanning(planTime);
        return updateScheduleVo;
    }

    /**
     * 选择计时类型
     */
    private void initTimingTypeListener() {
        timingTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString();
                Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
                if (position == Constants.TIMING_TYPE_DOWN) {
                    etPlanTime.setVisibility(View.VISIBLE);
                } else {
                    etPlanTime.setVisibility(View.GONE);
                }
                timingType = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void dismiss() {
        avi.setVisibility(View.GONE);
        avi.hide();
        dialog.dismiss();
    }

    @Override
    public void updateScheduleSuccess(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
        modifySuccessListener.modifySuccess();
    }

    @Override
    public void updateScheduleError(Resp resp) {
        avi.setVisibility(View.GONE);
        avi.hide();
        Toast.makeText(context, "修改失败，请检查网络连接", Toast.LENGTH_LONG);
    }


    private ModifySuccessListener modifySuccessListener;

    public void setModifySuccessListener(ModifySuccessListener modifySuccessListener) {
        this.modifySuccessListener = modifySuccessListener;
    }
}
